package com.aiflow.Action;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import util.Check;
import util.ServletHelp;

import com.aiflow.db.ConnDB;

//部门
public class DepartmentAction {

	// 查询字典
	public void findDepartment() {
		HttpServletRequest req = ServletActionContext.getRequest();
		ConnDB db = new ConnDB();
		Connection con = db.getConnection();
		Statement sta = null;
		ResultSet rs = null;
		JSONObject json = new JSONObject();
		List<Map<String, String>> datalist = new ArrayList<Map<String, String>>();
		JSONArray datas = new JSONArray();
		String id = req.getParameter("id");
		try {
			String sql = "select id,dept_name,code,pid from  department where 1=1 ";
			if (id != null && !id.equals("")) {
				sql += " and id = " + id;
			}
			sta = con.createStatement();
			rs = sta.executeQuery(sql);
			while (rs.next()) {
				Map<String, String> mapdata = new HashMap<String, String>();
				mapdata.put("id", rs.getString(1));
				mapdata.put("name", rs.getString(2));
				mapdata.put("code", rs.getString(3));
				mapdata.put("pid", rs.getString(4));
				datalist.add(mapdata);

			}
			datas = JSONArray.fromObject(datalist);
			json.put("success", true);
			json.put("datas", datas);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.closeRs(rs);
			db.closeStatement(sta);
			db.closeConnect(con);
		}
	}

	// 增加 部门
	public void addDepartment() {
		ConnDB db = new ConnDB();
		PreparedStatement ps = null;
		PreparedStatement psp = null;
		String name = ServletActionContext.getRequest().getParameter("name");
		String code = ServletActionContext.getRequest().getParameter("code");
		String pid = ServletActionContext.getRequest().getParameter("pid");
		JSONObject json = new JSONObject();
		Connection con = db.getConnection();
		Check ch = new Check();
		String sqll = "";
		try {
			boolean bool = ch.checkRepeat(name, "dept_name", "department");
			if (bool) {
				String sql = "insert into department(dept_name,code,leaf,pid) values(?,?,1,?)";
				if (pid != null && !pid.equals("0")) {
					sqll = "update department set leaf = 0 where id=?";
				}
				con.setAutoCommit(false);
				ps = con.prepareStatement(sql);
				int index = 0;
				ps.setString(++index, name);
				ps.setString(++index, code);
				ps.setString(++index, pid);
				ps.execute();
				if (pid != null && !pid.equals("0")) {
					psp = con.prepareStatement(sqll);
					psp.setString(1, pid);
					psp.execute();
				}
				con.commit();
				json.put("success", true);
			} else {
				json.put("success", false);
				json.put("message", name + "-- 名字重复");

			}
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			try {
				db.closeStatement(ps);
				db.closeStatement(psp);
				db.closeConnect(con);
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}
	}

	public void updateDictionary() {
		ConnDB db = new ConnDB();
		PreparedStatement ps = null;
		String name = ServletActionContext.getRequest().getParameter("name");
		String code = ServletActionContext.getRequest().getParameter("code");
		String id = ServletActionContext.getRequest().getParameter("id");
		Connection con = db.getConnection();
		try {
			String sql = "update department set dept_name = ?,code=? where id = ?";

			try {
				ps = con.prepareStatement(sql);
				int index = 0;
				ps.setString(++index, name);
				ps.setString(++index, code);
				ps.setString(++index, id);
				int rs = ps.executeUpdate();
				if (rs > 0) {
					// System.out.println("保存成功!!!");
				}
				JSONObject json = new JSONObject();
				json.put("success", true);
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				out.print(json);
				out.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}
	}

	// 删除 部门数据
	public void deleteDepartment() {
		ConnDB db = new ConnDB();
		Statement ps = null;
		Statement psDel = null;
		HttpServletRequest req = ServletActionContext.getRequest();
		String delId = req.getParameter("id");
		String iid = "";
		String sql = null;
		String sqlDel = null;
		Connection con = db.getConnection();
		ResultSet res = null;
		try {
			con.setAutoCommit(false);
			ps = con.createStatement();
			sql = "select id,pid from department "; // where id = 0
			res = ps.executeQuery(sql);
			String id = "";
			String pid = "";

			List list = new ArrayList<Map<String, String>>();
			List listdell = new ArrayList<Map<String, String>>();
			while (res.next()) {
				Map map = new HashMap<String, String>();
				id = res.getString(1);
				pid = res.getString(2);
				map.put("id", id);
				map.put("pid", pid);
				list.add(map);
			}
			psDel = con.createStatement();
			List<Map<String, String>> listt = getDeptId(delId, list, listdell);
			for (int i = 0; i < listt.size(); i++) {
				iid = (String) ((Map) listt.get(i)).get("id");
				sqlDel = "delete from department where id= " + iid;
				psDel.addBatch(sqlDel);
			}
			psDel.executeBatch();
			con.commit();
			JSONObject json = new JSONObject();
			json.put("success", true);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} finally {
			try {
				res.close();
				psDel.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}
	}

	public List getDeptId(String delId, List<Map<String, String>> list,
			List<Map<String, String>> listdel) {
		Map mp = null;
		for (int i = 0; i < list.size(); i++) {
			mp = list.get(i);
			if (delId.equals(mp.get("id"))) {
				break;
			}
		}
		listdel.add(mp);
		createTree(mp, list, listdel);
		return listdel;
	}

	public void createTree(Map<String, String> map,
			List<Map<String, String>> list, List<Map<String, String>> listdel) {
		Map<String, String> mapp = null;
		for (int i = 0; i < list.size(); i++) {
			mapp = list.get(i);
			if (map.get("id").equals(mapp.get("pid"))) {
				listdel.add(mapp);
				createTree(mapp, list, listdel);
			}
		}
	}

	// 查询字典 tree
	public void findTreeDepartment() {
		HttpServletRequest req = ServletActionContext.getRequest();

		ConnDB db = new ConnDB();
		Connection con = db.getConnection();
		Statement sta = null;
		ResultSet rs = null;
		JSONObject json = new JSONObject();
		List<Map<String, String>> datalist = new ArrayList<Map<String, String>>();
		JSONArray datas = new JSONArray();
		String whereSql = "";
		String sqlCount = "";
		String id = req.getParameter("id");

		try {
			String sql = "select id,dept_name,pid from  department where 1=1 ";
			if (id != null && id.equals("")) {
				sql += " and id = " + id;
			}
			sta = con.createStatement();

			rs = sta.executeQuery(sql);

			while (rs.next()) {
				Map<String, String> mapdata = new HashMap<String, String>();
				mapdata.put("id", rs.getString(1));
				mapdata.put("name", rs.getString(2));
				mapdata.put("pid", rs.getString(3));

				datalist.add(mapdata);

			}

			datas = JSONArray.fromObject(datalist);
			json.put("success", true);
			json.put("datas", datas);
			// json.put("results", index);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();

			out.print(json);
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.closeRs(rs);
			db.closeStatement(sta);
			db.closeConnect(con);
		}
	}

	// 获取 部门
	public void getDepartmentTree() {
		ConnDB db = new ConnDB();
		ResultSet rs = null;
		JSONArray datas = new JSONArray();
		String id = null;
		// 主树
		if ("-1".equals(ServletActionContext.getRequest().getParameter(
				"parentId"))) {
			id = "0";
		} else {
			id = ServletActionContext.getRequest().getParameter("parentId");
		}
		Connection con = db.getConnection();
		PreparedStatement ps = null;
		try {
			String sql = "select id,dept_name,leaf,pid,url from department where pid = "
					+ id;
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			try {
				while (rs.next()) {
					JSONObject allAlbum = new JSONObject();
					allAlbum.put("id", Integer.parseInt(rs.getString(1)));
					allAlbum.put("text", rs.getString(2));
					// 如果是0就是父节点
					if ("0".equals(rs.getString(3))) {
						allAlbum.put("leaf", false);
						// 如果是1就是子节点
					} else if ("1".equals(rs.getString(3))) {
						allAlbum.put("leaf", true);
					}
					allAlbum.put("pid", Integer.parseInt(rs.getString(4)));
					datas.add(allAlbum);
				}
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				out.print(datas.toString());
				out.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				rs.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
		}
	}

	// 取下拉菜单 (key/name)
	public static String getDepartmentCombo(String departmentId) {
		String sql = "";
		ConnDB db = new ConnDB();
		ResultSet rs = null;
		JSONArray datas = new JSONArray();
		String id = null;
		Map<String, String> allAlbum = null;
		Connection con = db.getConnection();
		PreparedStatement ps = null;
		String re = "";
		String sqlWhere ="";
		if(departmentId != null && !departmentId.equals("")){
			sqlWhere = " and pid="+departmentId ;
		}
		try {
			sql = "select id,dept_name  from department where 1=1  "
					+ sqlWhere + " order by id asc";

			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			allAlbum = new HashMap<String, String>();
			while (rs.next()) {

				allAlbum.put(rs.getString(1), rs.getString(2));

			}

			re = ServletHelp.getArrayFromMap(allAlbum, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {

				rs.close();
				ps.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
			return re;
		}
	}
	
	// 取下拉菜单 (key/name)
	public static String getDepartmentCombods(String departmentId) {
		String sql = "";
		ConnDB db = new ConnDB();
		ResultSet rs = null;
		JSONArray datas = new JSONArray();
		String id = null;
		Map<String, String> allAlbum = null;
		Connection con = db.getConnection();
		PreparedStatement ps = null;
		String re = "";
		String sqlWhere ="";
		if(departmentId != null && !departmentId.equals("")){
			sqlWhere = " and id="+departmentId ;
		}
		try {
			sql = "select id,dept_name  from department where 1=1  "
					+ sqlWhere + " order by id asc";

			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			allAlbum = new HashMap<String, String>();
			while (rs.next()) {
				allAlbum.put(rs.getString(1), rs.getString(2));
			}

			re = ServletHelp.getArrayFromMap(allAlbum, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {

				rs.close();
				ps.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
			return re;
		}

	}

	// 取下拉菜单 (name/name)
	public static String getDepartmentNameCombo(String departmentId) {
		String sql = "";
		ConnDB db = new ConnDB();
		ResultSet rs = null;
		JSONArray datas = new JSONArray();
		String id = null;
		Map<String, String> allAlbum = null;
		Connection con = db.getConnection();
		PreparedStatement ps = null;
		String re = "";
		String sqlWhere ="";
		if(departmentId != null && !departmentId.equals("")){
			sqlWhere = " and pid="+departmentId ;
		}
		try {
			sql = "select dept_name,dept_name  from department where 1=1 "
					+ sqlWhere + " order by id asc";

			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			allAlbum = new HashMap<String, String>();
			while (rs.next()) {
				allAlbum.put(rs.getString(1), rs.getString(2));
			}

			re = ServletHelp.getArrayFromMap(allAlbum, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				ps.close();
				con.close();
			} catch (Exception ex1) {
				ex1.printStackTrace();
			}
			return re;
		}

	}

}
